import {Layer, Text, Transformer} from "react-konva";
import {useRef} from "react";


export interface KonvaTextType {
    text: string;
    x?: number;
    y?: number;
    width?: number;
    height?: number;
    fill?: string;
    fontSize?: number;
    align?: string;
}

const KonvaText = (
    {
        data,
        isSelected = false,
        onKonvaClick
    }: {
        data?: KonvaTextType;
        isSelected: boolean;
        onKonvaClick?: () => void;
    }) => {
    const textRef = useRef(null);


    return (
        <Layer>
            <Text
                ref={textRef}
                draggable={isSelected}
                {...data}
                onClick={onKonvaClick}
                onDragMove={() => {

                }}
                onDragEnd={() => {
                    console.log(data);
                }}
                onTransform={(e) => {
                    e.target.setAttrs({
                        width: Math.max(e.target.width() * e.target.scaleX()),
                        height: Math.max(e.target.height() * e.target.scaleY()),
                        scaleX: 1,
                        scaleY: 1,
                    });
                }}
            />
            {isSelected && (
                <Transformer
                    nodes={[textRef.current]}
                    rotateAnchorOffset={20}
                    anchorCornerRadius={2}
                    borderDash={[2,2]}
                    anchorSize={6}
                />
            )}
        </Layer>
    )
}

export default KonvaText;